<script setup lang="tsx">
import { reactive, inject, defineComponent } from 'vue'
import {
  ElRow,
  ElCol,
  ElSteps,
  ElStep,
  ElMessageBox,
  ElMessage,
  type StepProps
} from 'element-plus'
import { ContentDetailWrap } from '@/components/ContentDetailWrap'
import { Table, TableColumn } from '@/components/Table'
import { useTable } from '@/hooks/web/useTable'
import { getDetailApi } from '@/api/document'
import { BaseButton } from '@/components/Button'
import { passStatusApi, rejectStatusApi } from '@/api/document'
const currentRow: any = inject('currentRow')
const emit = defineEmits(['close', 'get-list'])

const Setp = defineComponent({
  setup() {
    const statusMap: StepProps[][] = [
      [
        {
          title: '已提交',
          status: 'success',
          description: detailData.order_log[0] ? detailData.order_log[0].create_time : ''
        },
        { title: '待审核', status: 'process', description: '' },
        { title: '待入库', status: 'wait', description: '' },
        { title: '待完成', status: 'wait', description: '' }
      ],
      [
        {
          title: '已提交',
          status: 'success',
          description: detailData.order_log[0] ? detailData.order_log[0].create_time : ''
        },
        {
          title: '已审核',
          status: 'success',
          description: detailData.order_log[1] ? detailData.order_log[1].create_time : ''
        },
        { title: '待入库', status: 'wait', description: '' },
        { title: '待完成', status: 'wait', description: '' }
      ],
      [
        {
          title: '已提交',
          status: 'success',
          description: detailData.order_log[0] ? detailData.order_log[0].create_time : ''
        },
        {
          title: '已审核',
          status: 'success',
          description: detailData.order_log[1] ? detailData.order_log[1].create_time : ''
        },
        { title: '待入库', status: 'wait', description: '' },
        { title: '待完成', status: 'wait', description: '' }
      ],
      [
        {
          title: '已提交',
          status: 'success',
          description: detailData.order_log[0] ? detailData.order_log[0].create_time : ''
        },
        {
          title: '已拒绝',
          status: 'error',
          description: detailData.order_log[1] ? detailData.order_log[1].create_time : ''
        }
      ],
      [
        {
          title: '已提交',
          status: 'success',
          description: detailData.order_log[0] ? detailData.order_log[0].create_time : ''
        },
        {
          title: '已审核',
          status: 'success',
          description: detailData.order_log[1] ? detailData.order_log[1].create_time : ''
        },
        {
          title: '已入库',
          status: 'success',
          description: detailData.order_log[detailData.order_log.length - 1]
            ? detailData.order_log[detailData.order_log.length - 1].create_time
            : ''
        },
        {
          title: '已完成',
          status: 'success',
          description: detailData.order_log[detailData.order_log.length - 1]
            ? detailData.order_log[detailData.order_log.length - 1].create_time
            : ''
        }
      ]
    ]
    const index = detailData.order_status - 1
    const active = statusMap[index].findIndex((item) => item.status === 'error')
    return () => (
      <>
        <p>采购单进度条</p>
        <ElSteps active={active === -1 ? statusMap[index].length : active + 1} align-center>
          {statusMap[index].map((item) => {
            return <ElStep title={item.title} status={item.status} description={item.description} />
          })}
        </ElSteps>
        {detailData.order_status === 4 ? (
          <>
            <p>拒绝原因</p>
            <p>{detailData.order_log[1].remark}</p>
          </>
        ) : undefined}
      </>
    )
  }
})

const detailData = reactive<any>({})
const TableSchema = reactive<TableColumn[]>([
  {
    field: 'index',
    label: '序号',
    type: 'index'
  },
  {
    field: 'goods.name',
    label: '产品名称'
  },
  {
    field: 'spec_name',
    label: '规格'
  },
  {
    field: 'imgList',
    label: '图片',
    width: '100px'
  },
  {
    field: 'quantity',
    label: '数量'
  },
  {
    field: 'purchasing_price',
    label: '进货单价（元）'
  },
  {
    field: 'amount',
    label: '进货总价（元）'
  }
])
const { tableRegister, tableState, tableMethods } = useTable({
  immediate: false,
  fetchDataApi: async () => {
    const res = await getDetailApi(currentRow.id)
    Object.assign(detailData, res.data.info)
    return {
      list: res.data.info.details.map((val) => {
        const resultArray = val.goods.img.split(',')
        return {
          ...val,
          imgList: resultArray[0]
        }
      }),
      total: res.data.info.details.length
    }
  }
})
const { dataList } = tableState
tableMethods.getList()

const updateStatus = async (status) => {
  try {
    let remark: string | undefined = ''
    if (status === 5) {
      remark = await ElMessageBox.prompt('您是否要拒绝审核此单据？', '温馨提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        inputValidator: (value) => {
          if (value.length > 500) return '拒绝原因最多500字符！'
          if (value.length <= 0) return '请填写拒绝原因！'
          return true
        },
        inputPlaceholder: '请填写拒绝原因最多500字符'
      }).then(({ value }) => value)
      const res = await rejectStatusApi({ id: currentRow.id, remark })
      if (res) {
        ElMessage.success(res.msg)
        tableMethods.getList()
        emit('get-list')
      }
    } else {
      const res = await passStatusApi({ id: currentRow.id })
      if (res) {
        ElMessage.success(res.msg)
        tableMethods.getList()
        emit('get-list')
      }
    }
  } catch (err) {
    console.log(err)
  }
}
</script>

<template>
  <ContentDetailWrap title="采购单详情">
    <div style="margin-bottom: 20px">基础信息</div>
    <div v-if="detailData.company_user">
      <span style="margin-right: 20px">采购单据号: {{ detailData.no }}</span>
      <span style="margin-right: 20px">负责人: {{ detailData.company_user.real_name }}</span>
      <span style="margin-right: 20px">联系电话: {{ detailData.company_user.mobile }}</span>
      <span style="margin-right: 20px">公司地址: {{ detailData.company.address }}</span>
    </div>
    <div style="margin: 20px 0px">商品信息</div>
    <Table
      :columns="TableSchema"
      :data="dataList"
      :image-preview="['imgList']"
      max-height="500"
      :show-overflow-tooltip="false"
      @register="tableRegister"
    />
    <ElRow class="mt-[20px]" :gutter="20" v-if="!tableState.loading.value">
      <ElCol :span="12">单据备注：{{ detailData.remark }}</ElCol>
    </ElRow>
    <template #footer>
      <div class="mt-[20px]" v-if="!tableState.loading.value">
        <Setp />
      </div>
      <div class="w-full flex items-center justify-center mt-[20px]">
        <BaseButton @click="emit('close')">关闭</BaseButton>
        <template v-if="!tableState.loading.value && detailData.order_status === 1">
          <BaseButton type="warning" @click="updateStatus(5)">拒绝</BaseButton>
          <BaseButton type="primary" @click="updateStatus(2)">同意</BaseButton>
        </template>
      </div>
    </template>
  </ContentDetailWrap>
</template>
